# coding=utf-8
#

"""
装饰器集合
"""

from django.conf import settings

from iminer.sm_log import getLogger

from iminer.user.models import User

from iminer.utils.errorcode import ErrorResponse
from django.contrib.auth import login as django_login

try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps

logger = getLogger("iminer.utils.decorator")


def check_token(function=None):
    """ 检查给定的request在header中是否有一个合法的token,当前token使用ak123 """

    @wraps(function)
    def decorator(cls, request, *args, **kwargs):
        """ """
        token = request.environ.get("HTTP_AUTHENTICATION", "").strip()
        token = token or request.GET.get("token", "")

        if not token or token != "ak123":
            return ErrorResponse.get(ErrorResponse.INVALID_TOKEN)

        return function(cls, request, *args, **kwargs)

    return decorator


def check_user(function=None):
    """ 检查用户是否登录 """

    @wraps(function)
    def decorator(request, *args, **kwargs):
        """ 检查用户是否登录，如果未登录则跳转到登录页 """

        token = request.environ.get("HTTP_AUTHENTICATION", "")
        if not token:

            # 测试用例里，跟正式请求不一样
            try:
                token = request.environ["headers"]["Authentication"]
            except:
                token = ""

        if not token:
            return ErrorResponse.get(ErrorResponse.INVALID_USER_ID)

        user = User.objects.filter(token=token).first()

        if user:
            if user.is_active:
                django_login(request, user)
                setattr(request, "user", user)
        else:
            return ErrorResponse.get(ErrorResponse.INVALID_USER_ID)

        kwargs["user"] = request.user
        return function(request, *args, **kwargs)

    return decorator


def check_view_user(function=None):
    """ 检查给定的request在header中是否有一个合法的用户id """

    @wraps(function)
    def decorator(cls, request, *args, **kwargs):
        """ """
        token = request.environ.get("HTTP_AUTHENTICATION", "")
        if not token:

            # 测试用例里，跟正式请求不一样
            try:
                token = request.environ["headers"]["Authentication"]
            except:
                token = ""

        user = User.objects.filter(token=token).first()
        if user:
            if user.is_active:
                django_login(request, user)
                setattr(request, "user", user)
        else:
            return ErrorResponse.get(ErrorResponse.INVALID_USER_ID)

        kwargs["user"] = request.user
        return function(cls, request, *args, **kwargs)

    return decorator


def check_user_with_cache(function=None):
    """ 检查用户是否登录 """

    @wraps(function)
    def decorator(request, *args, **kwargs):
        """ 检查用户是否登录，如果未登录则跳转到登录页 """

        token = request.environ.get("HTTP_AUTHENTICATION", "")
        if not token:

            # 测试用例里，跟正式请求不一样
            try:
                token = request.environ["headers"]["Authentication"]
            except:
                token = ""

        if not token:
            return ErrorResponse.get(ErrorResponse.INVALID_USER_ID)

        if token == "ak123":
            pass
        else:
            user = User.objects.filter(token=token).first()

            if user:
                if user.is_active:
                    django_login(request, user)
                    setattr(request, "user", user)
            else:
                return ErrorResponse.get(ErrorResponse.INVALID_USER_ID)

            kwargs["user"] = request.user
        return function(request, *args, **kwargs)

    return decorator

